package com.shycloud.mido.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.common.security.util.SecurityUtils;
import com.shycloud.mido.member.api.entity.Member;
import com.shycloud.mido.member.api.entity.MultiClassroom;
import com.shycloud.mido.member.api.entity.MultiClassroomMemberAttend;
import com.shycloud.mido.member.api.entity.MultiStudentClassroomLink;
import com.shycloud.mido.member.api.entity.OrgStudentDetailed;
import com.shycloud.mido.member.api.vo.AddStudentInClassRoomVO;
import com.shycloud.mido.member.api.vo.AppMultiStudentClassroomVO;
import com.shycloud.mido.member.api.vo.MultiClassroomVO;
import com.shycloud.mido.member.api.vo.SmMemberTeacherGroupVO;
import com.shycloud.mido.member.api.vo.StudentVO;
import com.shycloud.mido.member.mapper.MemberMapper;
import com.shycloud.mido.member.mapper.MultiClassroomMapper;
import com.shycloud.mido.member.mapper.MultiClassroomMemberAttendMapper;
import com.shycloud.mido.member.mapper.MultiStudentClassroomLinkMapper;
import com.shycloud.mido.member.mapper.MultiTeacherClassroomLinkMapper;
import com.shycloud.mido.member.mapper.OrgStudentDetailedMapper;
import com.shycloud.mido.member.mapper.SmMemberTeacherGroupMapper;
import com.shycloud.mido.member.mapper.TeacherMapper;
import com.shycloud.mido.member.service.MultiStudentClassroomLinkService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 学生加入教室业务实现类
 *
 * @author baiqiang
 * @since 2021-07-12
 */
@Service
@AllArgsConstructor
public class MultiStudentClassroomLinkServiceImpl extends
		ServiceImpl<MultiStudentClassroomLinkMapper, MultiStudentClassroomLink> implements MultiStudentClassroomLinkService {

	/** 学生模块 mapper */
	private final OrgStudentDetailedMapper studentDetailedMapper;
	/** 加入班级记录信息 mapper */
	private final MultiClassroomMemberAttendMapper attendMapper;
	/** 教师分组模块 mapper */
	private final SmMemberTeacherGroupMapper groupMapper;
	/** 教师模块 mapper */
	private final TeacherMapper teacherMapper;
	/** 班级教师模块 mapper */
	private final MultiTeacherClassroomLinkMapper teacherClassroomLinkMapper;
	/** 班级模块 mapper */
	private final MultiClassroomMapper multiClassroomMapper;
	/** 用户模块 mapper */
	private final MemberMapper memberMapper;

	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public boolean addStudent(AddStudentInClassRoomVO addStudentInClassRoomVO) {

		// 班级ID
		String classroomId = addStudentInClassRoomVO.getClassroomId();

		if (SecurityUtils.getMember() != null) {
			// 获取班级信息
			MultiClassroom classroom = multiClassroomMapper.selectById(classroomId);
			if (classroom != null && !SecurityUtils.getMember().getId().equals(classroom.getCreateUser())) {
				throw new BusinessException("此教师不是教室创建者,无法添加学生");
			}
		}

		//用户ID
		String memberId;
		//学生ID
		String studentId;

		//判断是否有此学生
		OrgStudentDetailed studentDetailed = studentDetailedMapper.getStudentByUsername(addStudentInClassRoomVO.getUsername());

		if (studentDetailed != null) {

			memberId = studentDetailed.getMemberId();
			studentId = studentDetailed.getId();

			//判断此用户是否是教师身份
			Member member = memberMapper.selectById(memberId);

			if ("1".equals(member.getIsTeacher())) {
				throw new BusinessException("此用户为教师身份,无法添加");
			}

			Integer classRoomCount = baseMapper.selectCount(new QueryWrapper<MultiStudentClassroomLink>()
					.eq("student_id", studentId)
					.eq("classroom_id", classroomId));

			if (classRoomCount > 0) {
				throw new BusinessException("此学生已经加入此班级,无需重复添加");
			}

		} else {
			throw new BusinessException("未查询到此学生,请重新输入");
		}

		//记录信息
		MultiClassroomMemberAttend attend = addMultiClassroomMemberAttend(memberId, "0");
		//添加学生进教室
		addMultiStudentClassRoom(addStudentInClassRoomVO, studentId, attend);

		return true;
	}

	@Override
	public Map<String, List<AppMultiStudentClassroomVO>> getStudentList(String teacherId, String studentName) {

		//定义响应结构体
		List<AppMultiStudentClassroomVO> groupList = new ArrayList<>();
		List<AppMultiStudentClassroomVO> classList = new ArrayList<>();

		//查询未分组学生
		IPage<StudentVO> studentDetailNonGroup = teacherMapper.getStudentDetailV2(new Page(1, 999999), -1, teacherId, studentName);
		//================ 先处理未分组的人员 START ============================================================//
		AppMultiStudentClassroomVO appMultiStudentClassroomVONon = new AppMultiStudentClassroomVO();
		appMultiStudentClassroomVONon.setGroupId(-1);
		appMultiStudentClassroomVONon.setStudentCount((int) studentDetailNonGroup.getTotal());
		appMultiStudentClassroomVONon.setClassOrGroupName("未分组");
		//插入学生信息
		appMultiStudentClassroomVONon.setStudents(studentDetailNonGroup.getRecords());
		groupList.add(appMultiStudentClassroomVONon);
		//================ 先处理未分组的人员 E-N-D ============================================================//
		List<SmMemberTeacherGroupVO> teacherGroupList = groupMapper.getGroupList(teacherId);
		for (SmMemberTeacherGroupVO smMemberTeacherGroupVO : teacherGroupList) {
			AppMultiStudentClassroomVO appMultiStudentClassroomVO = new AppMultiStudentClassroomVO();
			appMultiStudentClassroomVO.setClassOrGroupName(smMemberTeacherGroupVO.getName());
			appMultiStudentClassroomVO.setGroupId(smMemberTeacherGroupVO.getId());
			//获取分组下学生列表
			IPage<StudentVO> studentDetailGroup = teacherMapper
					.getStudentDetailV2(new Page(1, 999999), smMemberTeacherGroupVO.getId(), teacherId, studentName);
			appMultiStudentClassroomVO.setStudentCount((int) studentDetailGroup.getTotal());
			appMultiStudentClassroomVO.setStudents(studentDetailGroup.getRecords());
			groupList.add(appMultiStudentClassroomVO);
		}

		// 查询班级列表
		List<MultiClassroomVO> multiClassrooms = teacherClassroomLinkMapper.getClassRoomListByTeacherId(teacherId);

		for (MultiClassroom multiClassroom : multiClassrooms) {
			AppMultiStudentClassroomVO appMultiStudentClassroomVO = new AppMultiStudentClassroomVO();
			appMultiStudentClassroomVO.setClassOrGroupName(multiClassroom.getName());
			appMultiStudentClassroomVO.setClassroomId(multiClassroom.getId());
			appMultiStudentClassroomVO.setScope(multiClassroom.getScope());
			List<StudentVO> classroomStudent = baseMapper.getClassroomStudent(multiClassroom.getId(), teacherId, studentName);
			appMultiStudentClassroomVO.setStudentCount(classroomStudent.size());
			appMultiStudentClassroomVO.setStudents(classroomStudent);
			classList.add(appMultiStudentClassroomVO);
		}

		Map<String, List<AppMultiStudentClassroomVO>> resMap = new HashMap(2);
		resMap.put("groupList", groupList);
		resMap.put("classList", classList);
		return resMap;
	}

	@Override
	public List<StudentVO> getStudentListByRoomId(String classroomId) {
		return baseMapper.getClassroomStudent(classroomId, null, null);
	}

	/**
	 * 添加学生进教室
	 *
	 * @param addStudentInClassRoomVO 学生-教室信息
	 * @param studentId               学生ID
	 * @param attend                  记录信息
	 * @return null
	 * @author nianhua.jiang
	 * @date 2021/7/27 10:09
	 */
	private void addMultiStudentClassRoom(AddStudentInClassRoomVO addStudentInClassRoomVO, String studentId,
			MultiClassroomMemberAttend attend) {

		MultiStudentClassroomLink multiStudentClassroomLink = new MultiStudentClassroomLink();
		//班级ID
		multiStudentClassroomLink.setClassroomId(addStudentInClassRoomVO.getClassroomId());
		//记录表ID
		multiStudentClassroomLink.setAttendId(attend.getId());
		//创建时间
		multiStudentClassroomLink.setCreateTime(LocalDateTime.now());
		//学生
		multiStudentClassroomLink.setMonitor("0");
		//机构ID
		multiStudentClassroomLink.setOrgId(addStudentInClassRoomVO.getOrgId());
		//学生ID
		multiStudentClassroomLink.setStudentId(studentId);

		baseMapper.insert(multiStudentClassroomLink);
	}

	/**
	 * 记录学生加入教室信息
	 *
	 * @param memberId 用户ID
	 * @return com.shycloud.mido.member.api.entity.MultiClassroomMemberAttend
	 * @author nianhua.jiang
	 * @date 2021/7/27 10:06
	 */
	private MultiClassroomMemberAttend addMultiClassroomMemberAttend(String memberId, String attendType) {
		MultiClassroomMemberAttend attend = new MultiClassroomMemberAttend();
		//用户 MemberId
		attend.setAppointUserId(memberId);
		//申请时间
		attend.setAttendTime(LocalDateTime.now());
		//申请类型 0加入 1退出
		attend.setAttendType("0");
		//申请客户端 - web
		attend.setAttendUserClient("0");
		//默认机构审核通过
		attend.setCheckerType("2");
		//有效数据
		attend.setDelFlag(CommonConstants.STATUS_NORMAL);
		//已通过
		attend.setStatus("1");
		//学生
		attend.setType("0");
		//创建时间
		attend.setCreateTime(LocalDateTime.now());
		attendMapper.insert(attend);
		return attend;
	}

	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public boolean delStudent(String studentId, String classroomId) {

		//获取学生信息
		OrgStudentDetailed studentDetailed = studentDetailedMapper.selectById(studentId);
		//1.踢出学生
		baseMapper.delete(new QueryWrapper<MultiStudentClassroomLink>().eq("student_id", studentId).eq("classroom_id", classroomId));
		//2.记录信息
		addMultiClassroomMemberAttend(studentDetailed.getMemberId(), "1");

		return true;

	}

}
